#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008  Vladimir Lagunov

import cPickle
from config import *

try:
	basefile = open(basename, 'r')
	UserBase = cPickle.load(basefile)
	basefile.close()
except (IOError, EOFError):
	basefile = open(basename, 'w')
	cPickle.dump([], basefile)
	UserBase = []
	basefile.close()

def findUser(x):
	for i in xrange(len(UserBase)):
		if UserBase[i][0] == x:
			return i
	return -1

def addUser(x):
	UserBase.append([x, 0])
	updateBase()

def addScore(x, n=None):
	if n == None:
		n = 1
	i = findUser(x)
	if i != -1:
		UserBase[i][1] += n
	updateBase()

def sortByScore():
	cpc = []
	for y, x in UserBase:
		cpc.append([x, y])
	cpc.sort()
	ncpc = []
	for y, x in cpc:
		ncpc.append([x, y])
	del cpc
	return ncpc


def updateBase():
	global basefile, UserBase
	basefile = open(basename, 'w')
	cPickle.dump(UserBase, basefile)
	basefile.flush()
	basefile.close()

def swapDictElems(x):
	copydict = {}
	for i in x.keys():
		copydict[x[i]] = i
	return copydict

